package com.hbt.myplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.hbt.myplus.model.*;
import com.hbt.myplus.service.impl.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.hbt.myplus.service.IRegService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hbt.myplus.utils.ResponseWeb;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
    *  前端控制器
    * </p>
 *
 * @author astupidcoder
 * @since 2020-12-22
 * @version v1.0
 */
@RestController
@RequestMapping("reg")


public class RegController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private RegServiceImpl regService;

    @Autowired
    private SectionServiceImpl sectionService;

    @Autowired
    private DoctorServiceImpl doctorService;

    @Autowired
    private PetOwnServiceImpl petOwnService;

    @Autowired
    private PetServiceImpl petService;

    @Autowired
    private DrugServiceImpl drugService;

    @Autowired
    private RegDrugServiceImpl regDrugService;

    @Autowired
    private PayServiceImpl payService;

    @Autowired
    private TraceServiceImpl traceService;

    @Autowired ImgServiceImpl imgService;

    /**
     * 查询分页数据
     */
    @GetMapping(value = "/s")
    public ResponseWeb<Page> findListByPage(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,@RequestParam(name = "pageSize", defaultValue = "20") int pageSize){
        return null;
    }

    //就诊
    @PostMapping("/submit_treat")
    @Transactional
    public ResponseWeb submitTreat(@RequestBody Map map){
        System.out.println(map.toString());
        if (map.get("regId") == null){
            return ResponseWeb.fail("挂号单号不能为null");
        }
        int regId = (int)(map.get("regId") == null?0:map.get("regId"));
        String treatSug = (String) (map.get("treatSug") == null?"":map.get("treatSug"));
        List<Map> drugMapList = (List<Map>) (map.get("drug_list") == null? new ArrayList<>():map.get("drug_list"));
        List<RegDrug> regDrugInsertList = new ArrayList<>();
        List<RegDrug> regDrugUpdateList = new ArrayList<>();
        //添加reg_drug
        if (drugMapList != null && drugMapList.size() > 0){
            drugMapList.stream().filter(a -> (Integer) (a.get("id")) != null)
                    .forEach(a ->{
                        RegDrug regDrug = new RegDrug();
                        regDrug.setDrugId(Integer.parseInt(a.get("id").toString()));
                        regDrug.setRegId(regId);
                        regDrug.setCount(Integer.parseInt(a.get("count").toString()));
                        regDrug.setV(a.get("v") == null? "":a.get("v").toString());
                        regDrug.setC(a.get("c") == null? "": a.get("c").toString());
                        if (a.get("isNew") !=null &&(Integer)a.get("isNew")== 1){
                            RegDrug one = regDrugService.getOne(new QueryWrapper<RegDrug>().eq("reg_id", regDrug.getRegId()).eq("drug_id", regDrug.getDrugId()));
                            if (one != null){
                                System.out.println(one);
                                System.out.println(regDrug);
                                one.setCount(regDrug.getCount()+one.getCount());
                                one.setC(regDrug.getC());
                                one.setV(regDrug.getV());
                                regDrugUpdateList.add(one);
                            }else {
                                regDrugInsertList.add(regDrug);
                            }//     <image class='list_img_tab1'  src='../../static/trace.png'></image>
                        }else {
                            RegDrug one = regDrugService.getOne(new QueryWrapper<RegDrug>().eq("reg_id", regDrug.getRegId()).eq("drug_id", regDrug.getDrugId()));
                            one.setC(regDrug.getC());
                            one.setV(regDrug.getV());
                            regDrugUpdateList.add(one);
                        }
                    });
            if (regDrugInsertList.size()>0){
                regDrugService.saveBatch(regDrugInsertList);
            }
            if (regDrugUpdateList.size()>0){
                regDrugService.updateBatchById(regDrugUpdateList);
            }
        }

        Reg reg = regService.getById(regId);

        //添加trace记录
        if (reg.getIsTreat() == 0){
            Trace trace = new Trace();
            trace.setTime(new Date());
            trace.setContent("已就诊");
            trace.setRegId(regId);
            traceService.save(trace);
        }

        //更新reg
        reg.setTreatSug(treatSug);
        reg.setId(regId);
        reg.setIsTreat(1);
        reg.setStatus("已就诊");
        regService.updateById(reg);

        return new ResponseWeb("成功提交");
    }


    /**
     * 查询分页数据
     */
    @GetMapping(value = "/all")
    public ResponseWeb<List<Reg>> findListByPage(@RequestHeader(value = "openid", required = false) String openid, @RequestParam(value = "docId", required = false) Integer docId){
        List<Reg> list = null;
        if(openid == null || openid.trim().length()==0){
            list = regService.list(new QueryWrapper<Reg>().eq("delete_flag", 0).orderByDesc("create_time"));
        }else{
            list = regService.list(new QueryWrapper<Reg>().eq("delete_flag", 0).eq("pet_own_id", openid).orderByDesc("create_time"));
        }
        if(list == null || list.size() == 0){
            return new ResponseWeb(new ArrayList());
        }
        //过滤信息
        if (!StringUtils.isEmpty(docId))
        list = list.stream().filter(a -> a.getDoctorId().equals(docId)).collect(Collectors.toList());

        if (list.isEmpty()){
            return new ResponseWeb(new ArrayList(0));
        }

        //获取宠物信息
        List<Integer> petIdList = list.stream().map(a -> a.getPetId()).collect(Collectors.toList());
        List<Pet> petList = (List<Pet>) petService.listByIds(petIdList);

        //获取宠物主信息
        List<String> petownIds = list.stream().map(a -> a.getPetOwnId()).distinct().collect(Collectors.toList());
        List<PetOwn> petowns = (List<PetOwn>) petOwnService.list(new QueryWrapper<PetOwn>().in("openid", petownIds));

        //根据ids获取门诊
        Stream<Integer> integerStream = list.stream().map(Reg::getSectionId);
        List<Integer> sectionIds = integerStream.collect(Collectors.toList());
        List<Section> sections = (List<Section>)sectionService.listByIds(sectionIds);

        //工具ids获取医生信息
        Stream<Integer> doc_stream = list.stream().map(a -> a.getDoctorId());
        List<Integer> docIds_list = doc_stream.collect(Collectors.toList());
        List<Doctor> doctors = (List<Doctor>)doctorService.listByIds(docIds_list);

        //获取所有的挂号单号的img
        List<Img> reportList = imgService.list(new QueryWrapper<Img>().eq("field", Reg.REPORT));
        if (reportList == null)reportList = new ArrayList<>(0);

        //根据regId获取
        List<Trace> traceList = traceService.list();



        for (Reg re : list) {
            List<Section> sectionList = sections.stream().filter(a -> a.getId().equals(re.getSectionId())).collect(Collectors.toList());
            if (!sectionList.isEmpty()){
                re.setSection(sectionList.get(0));
            }
            List<Doctor> doctorList = doctors.stream().filter(a -> a.getId().equals(re.getDoctorId())).collect(Collectors.toList());
            if (!doctorList.isEmpty()){
                re.setDoctor(doctorList.get(0));
            }

            List<PetOwn> petOwnList = petowns.stream().filter(a -> a.getOpenid().equals(re.getPetOwnId())).collect(Collectors.toList());
            if (!doctorList.isEmpty()){
                re.setPetOwn(petOwnList.get(0));
            }

            List<Trace> traces = traceList.stream().filter(a -> a.getRegId().equals(re.getId())).collect(Collectors.toList());
            if (traces != null && traces.size()>0){
                re.setTraceList(traces);
            }else {
                re.setTraceList(new ArrayList<>(0));
            }

            List<Img> reports = reportList.stream().filter(a -> a.getInsId().equals(re.getId())).collect(Collectors.toList());
            re.setReportList(reports);

            //获取宠物信息
            List<Pet> pets = petList.stream().filter(a -> a.getId().equals(re.getPetId())).collect(Collectors.toList());
            if (!pets.isEmpty()){
                re.setPet(pets.get(0));
            }
        }
        return new ResponseWeb<>(list);
    }


    /**
     * 根据id查询
     */
    @GetMapping(value = "/{id}")
    public ResponseWeb<Reg> getById(@PathVariable("id") String id){
       return null;
    }

    /**
     * 根据id查询
     */
    @GetMapping(value = "/seedoctor/{regNO}")
    public ResponseWeb<Map> getByRegNo(@PathVariable("regNO") String regNo){
        //获取挂号信息
        Reg reg = regService.list(new QueryWrapper<Reg>().eq("reg_no", regNo)).get(0);
        reg.setSection(sectionService.getById(reg.getSectionId()));
        //根据挂号信息中的openid获取宠物主信息
        PetOwn petOwn = petOwnService.list(new QueryWrapper<PetOwn>().eq("openid", reg.getPetOwnId())).get(0);
        //根据挂号信息中的宠物id获取宠物信息
        Pet pet = petService.list(new QueryWrapper<Pet>().eq("id", reg.getPetId())).get(0);
        //获取挂号中的药物信息
        List<Drug> drugs = drugService.getBaseMapper().getDrugListByRegId(reg.getId());
        reg.setDrugList(drugs);
        //获取挂号单报告
        List<Img> reportList = imgService.list(new QueryWrapper<Img>().eq("ins_id", reg.getId()).eq("field", Reg.REPORT).eq("tbname", "reg"));
        reg.setReportList(reportList);

        Map<String, Object> map = new HashMap<>();
        map.put("reg", reg);
        map.put("petOwn", petOwn);
        map.put("pet", pet);
        return new ResponseWeb(map);
    }


    /**
     * 新增
     */
    @PostMapping
    @Transactional
    public ResponseWeb<Reg> add(@RequestBody Reg reg, @RequestHeader("openid") String openid){
        System.out.println(reg.toString());
        reg.setRegNo(UUID.randomUUID().toString());
        Date now = new Date();
        reg.setCreateTime(now);
        reg.setPayTime(now);
//        reg.setStartTime(now);
        reg.setEndTime(now);
        reg.setIsPay(1);
        reg.setIsTreat(0);
        reg.setPetOwnId(openid);
        reg.setDeleteFlag(0);
        reg.setStatus("已经支付");
        System.out.println(reg);
        regService.save(reg);


        //增加缴费信息
        Pay pay = new Pay();
        pay.setItemname("挂号缴费");
        pay.setPoid(openid);
        pay.setPrice(reg.getMoney());
        pay.setTime(new Date());
        pay.setSno(UUID.randomUUID().toString());
        payService.save(pay);

        Date date = new Date();

        //增加挂号记录
        Trace regTrace = new Trace();
        regTrace.setContent("已挂号");
        regTrace.setRegId(reg.getId());
        regTrace.setTime(date);

        //增加缴费记录
        date.setTime(date.getTime()+10);
        Trace payTrace = new Trace();
        payTrace.setContent("已缴费");
        payTrace.setRegId(reg.getId());
        payTrace.setTime(date);

        List<Trace> traceList = new ArrayList<>();
        traceList.add(regTrace);
        traceList.add(payTrace);
        traceService.saveBatch(traceList);

        return new ResponseWeb("挂号成功");
    }

    /**
     * 删除
     */
    @DeleteMapping
    public ResponseWeb<String> delete(@RequestParam("ids") List<String> ids){
        return null;
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseWeb<Reg> update(@RequestBody Reg reg){
        return null;
     }

}
